package com.example.sunsg.okhttptest.customview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.Log;

/**
 * Created by Administrator on 2016/11/1.
 */
public class GradientTextView extends android.support.v7.widget.AppCompatTextView {
    private static final boolean DEBUG = true;
    private static final String TAG = "GradientTextView";

    private static final int LIGHT_COLOR = 0xffffffff;
    private static final int TEXT_COLOR = 0xff2196f3;
    private static final int ANIMATION_INTERVAL = 50;
    private static final int ANIMATION_SECTION = 20;

    private LinearGradient mLinearGradient;
    private Matrix mGradientMatrix;
    private Paint mPaint;
    private int mViewHeight = 0;
    private int mTranslate = 0;
    private int mLightColor = LIGHT_COLOR;
    private int mTextColor = TEXT_COLOR;
    private boolean mSlide = true;

    public GradientTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setShader() {
        if(!mSlide){
            return;
        }
        mLinearGradient = new LinearGradient(0, -mViewHeight, 0, 0, new int[]{mTextColor, mLightColor, mTextColor},
                new float[]{0, 0.5f, 1f}, Shader.TileMode.CLAMP);
        if (mPaint == null) {
            mPaint = getPaint();
        }
        if (mGradientMatrix == null) {
            mGradientMatrix = new Matrix();
        }
        mPaint.setShader(mLinearGradient);
        if (DEBUG) {
            Log.i(TAG, "setShader = ");
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (mViewHeight == 0) {
            mViewHeight = getMeasuredHeight();
            if (mViewHeight > 0) {
                setShader();
            }
        }
        if (DEBUG) {
            Log.i(TAG, "onSizeChanged mViewHeight= " + mViewHeight);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if(!mSlide){
            return;
        }
        if (DEBUG) {
//            Log.i(TAG, "onDraw mTranslate= " + mTranslate);
        }
        if (mGradientMatrix != null) {
            mTranslate += mViewHeight / ANIMATION_SECTION;
            if (mTranslate >= 2 * mViewHeight) {
                mTranslate = 0;
            }
            mGradientMatrix.setTranslate(0, mTranslate);
            mLinearGradient.setLocalMatrix(mGradientMatrix);
            postInvalidateDelayed(ANIMATION_INTERVAL);
        }
//        mPaint.setTextSize(50);
        canvas.drawText("78%",0,200,mPaint);
    }

//    public void setTextColor(int color){
//        super.setTextColor(color);
//        mSlide = false;
//        mLinearGradient = null;
//    }
}
